package de.ret_world.openrpgstudio.engine.loading;

import org.apache.log4j.Logger;
import org.jrabbit.base.core.loop.Loop;
import org.jrabbit.base.input.KeyboardHandler;
import org.jrabbit.base.input.MouseHandler;
import org.jrabbit.base.managers.Resources;
import org.jrabbit.base.managers.window.WindowManager;
import org.jrabbit.standard.game.objects.specialized.TextSprite;
import org.jrabbit.standard.game.world.World;
import org.lwjgl.LWJGLException;

/**
 *
 * @author Emu
 */
public class LoadingLoop extends Loop {

    private World world;
    private InitializeScriptsThread thread;

    public LoadingLoop(com.artemis.World entityWorld) {
        Resources.images().setImageSmooth(true);
        world = new World();
        TextSprite loadText = new TextSprite("Loading...");
        world.add(loadText);
        Logger.getLogger(LoadingLoop.class).info("Loading Resources...");

        thread = new InitializeScriptsThread(entityWorld);
        thread.start();
    }

    @Override
    protected void start() {
        MouseHandler.hideMouse(true);
    }

    @Override
    protected void end() {
        Logger.getLogger(LoadingLoop.class).info("Loaded all Resources!");
    }

    @Override
    public void update(int delta) {
        KeyboardHandler.update();
        if (thread.contextSharingFailed()) {
            render();
            thread.act();
            exit();
        } else if (thread.complete()) {
            exit();
        } else {
            world.update(delta);
        }
    }

    @Override
    public void render() {
        WindowManager.controller().beginRender();
        world.render();
        WindowManager.controller().endRender();
    }
}
